//
//  VGPlayerViewController.swift
//  vgbox
//
//  Created by 宋海胜 on 2019/4/11.
//  Copyright © 2019年 Swift Xcode. All rights reserved.
//  视频播放vc

import UIKit

class VGPlayerViewController: UIViewController {
    fileprivate var videoUrl: String!
    fileprivate var totalTime: CGFloat = 0
    fileprivate var playSuccess: Bool = false
    
    fileprivate lazy var saveVideoV: UIView = {
        let V: UIView = UIView(frame: self.view.frame)
        V.backgroundColor = UIColor.clear
        let longGestrue = UILongPressGestureRecognizer(target: self, action: #selector(self.saveVideo(_:)))
        V.addGestureRecognizer(longGestrue)
        return V
    }()
    
    fileprivate lazy var closeBt: UIButton = {
        let bt: UIButton = UIButton(frame: CGRect(x: 0, y: 20, width: 60, height: 60))
        bt.setImage(UIImage(named: "close_ico"), for: .normal)
        bt.addTarget(self, action: #selector(hidePlayerView), for: .touchUpInside)
        return bt
    }()
    
    fileprivate lazy var progressView: VGVideoProgressView = {
        
        let view: VGVideoProgressView = VGVideoProgressView(frame: CGRect(x: 0, y: SCREEN_HEIGHT - (IS_PHONEX ? 60 : 45), width: SCREEN_WIDTH, height: 30))
        view.playOrPauseClosure = {
            if self.playSuccess {
                DGCacheVideoPlayer.shareInstance().seekTime(0)
            }
            self.playOrPause()
        }
        view.sliderChangeClosure = { (value: Float) in
            DGCacheVideoPlayer.shareInstance().seekTime(UInt(CGFloat(value) * self.totalTime))
        }
        view.fullScreenClosure = {
        }
        
        return view
    }()
    
    init(url: String) {
        super.init(nibName: nil, bundle: nil)
        videoUrl = url
    }
    
    deinit {
        print("VGPlayerViewController 释放啦")
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .black
        
        setVideoPlayer()
        
        view.addSubview(saveVideoV)
        view.addSubview(closeBt)
        view.addSubview(progressView)
    }
    
    @objc func hidePlayerView() {
        DGCacheVideoPlayer.shareInstance().play(DGCacheVideoOperate.stop)
        dismissViewController()
    }
    
    fileprivate func setVideoPlayer() {
        let model: DGCacheVideoModel = DGCacheVideoModel()
        model.playId = "0"
        model.playUrl = videoUrl!
        DGCacheVideoPlayer.shareInstance().dgCacheVideoDelegate = self
        DGCacheVideoPlayer.shareInstance().setPlayList([model], offset: 0, videoGravity: AVLayerVideoGravity(rawValue: convertFromAVLayerVideoGravity(AVLayerVideoGravity.resizeAspect)), addViewLayer: view.layer, isCache: true, layerFrame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
    }
    
    fileprivate func playOrPause() {
        switch DGCacheVideoPlayer.shareInstance().currentPlayeStatus() {
        case DGCacheVideoState.play:
            DGCacheVideoPlayer.shareInstance().play(DGCacheVideoOperate.pause)
        case DGCacheVideoState.pause:
            DGCacheVideoPlayer.shareInstance().play(DGCacheVideoOperate.play)
        case DGCacheVideoState.buffer:
            DGCacheVideoPlayer.shareInstance().play(DGCacheVideoOperate.play)
        case DGCacheVideoState.stop:
            DGCacheVideoPlayer.shareInstance().play(DGCacheVideoOperate.pause)
        default:
            break
        }
    }
}

extension VGPlayerViewController: DGCacheVideoPlayerDelegate {
    func dgCacheVideoPlayFailed(_ error: Error) {
        self.view.makeToast("播放失败", duration: 1.0)
    }
    
    func dgCacheVideoPlayFinish(_ nextModel: DGCacheVideoModel) {
        playSuccess = true
        print("播放成功")
    }
    
    func dgCacheVideoPlayStatusChanged(_ status: DGCacheVideoState) {
        print("播放状态改变\(status)")
        progressView.setPlayState(play: status == .play)
    }
    
    func dgCacheVideoCacheProgress(_ cacheProgress: CGFloat) {
        print("下载进度\(cacheProgress)")
        progressView.setProgress(float: Float(cacheProgress))
    }
    
    func dgCacheVideoPlayerCurrentTime(_ currentTime: CGFloat, duration durationTime: CGFloat, playProgress: CGFloat) {
        print("播放数据显示-currentTime\(currentTime)-durationTime-\(durationTime)-playProgress-\(playProgress)")
        progressView.setSlider(float: Float(playProgress))
        progressView.setCurrentTime(time: currentTime)
        progressView.setTotalTime(time: durationTime)
        totalTime = durationTime
    }
}

// MARK: - 长按保存视频
extension VGPlayerViewController {
    @objc fileprivate func saveVideo(_ sender: UIGestureRecognizer) {
        if sender.state == .began {
//            alertV.show(ctr: self)
//            alertV.callbacktouchAny = { [weak self] Index in
//                self?.alertV.hideView()
//                if Index == 0 {
//                    self.view.makeToast(HudText.saving, duration: 100.0)
//                    PhotoAlbumUtil.saveVideoInAlbum(url: videoURL, albumName: SystemUtils.getAppName(), completion: { [weak self] result in
//                        DispatchQueue.main.async {
//                            self?.view.hideToast()
//                            self?.dealWithImageVideoResult(result)
//                        }
//                    })
//                } else {
//                    self?.dealWithImageVideoResult(.error)
//                }
//            }
        }
    }
    
    private func dealWithImageVideoResult(_ result: PhotoAlbumUtilResult) {
        switch result {
        case .success:
            self.view.makeToast("已保存到系统相册", duration: 1.0)
        case .denied:
            String.sy_OpenURL(ctr: self, title: "无法访问相册", message: "请在iPhone的“设置-隐私-照片”中允许\(String.getAppName())访问你的照片")
        case .error:
            self.view.makeToast("保存失败", duration: 1.0)
        default:
            break
        }
    }
}

// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromAVLayerVideoGravity(_ input: AVLayerVideoGravity) -> String {
    return input.rawValue
}
